import React from 'react';
import { connect } from 'dva';
import jrQrcode from 'jr-qrcode';

import { Modal, Form, Input } from 'antd';
const FormItem = Form.Item;

const loadImg = (src) => {
    const paths = Array.isArray(src) ? src : [src];
    const promise = [];
    paths.forEach((path) => {
        promise.push(new Promise((resolve, reject) => {
            let img = new Image();
            img.crossOrigin = "Anonymous";
            img.src = path;
            img.onload = () => {
                resolve(img);
            };
            img.onerror = (err) => {
                console.log('图片加载失败')
            }
        }))
    });
    return Promise.all(promise);

}

const getImageData = async (url, src, x, y, w) => {
    const imgsrc = jrQrcode.getQrBase64(url)
    const [img1, img2] =  await loadImg([imgsrc, src])

    let canvas = document.createElement('canvas')

    const width = img2.width
    const height = img2.height

    const [x2,y2,w2 ] = [
      Math.round( width * x / 100 ),
      Math.round(height * y / 100 ),
      Math.round( width * w / 100 )
    ]

    canvas.width = width*2
    canvas.height = height*2
    let ctx = canvas.getContext("2d")

        ctx.drawImage(img2, 0, 0, width*2, height*2)
        ctx.drawImage(img1, x2*2, y2*2, w2*2, w2*2)
        ctx.save()
        let imageURL = canvas.toDataURL("image/png")

    return imageURL

}



@connect(({ partnerOrgModel }) => ({ partnerOrgModel }))
class FormCreate extends React.Component {
  componentDidMount(){
    // 获取多对一字段的下拉列表框选项所需要的数据
  }

  handleCancel(){
    const { dispatch } = this.props;
        dispatch({
          type: 'partnerOrgModel/hide',
          payload: 'editForm'
        });
  }

  handleOk(){
    const { dataSource: record, form: { validateFields } } = this.props;
    const { dispatch } = this.props;
    validateFields( async  (err, values) => {
      if (!err) {

        const {x,y,w} = JSON.parse(record.ref)
        const image = `data:image/jpeg;base64,${escape(record.image)}`
        console.log(x,y,w)

        const { email } = values

          const newImage = await getImageData(email,
              image, x,y,w )

          const image2 = unescape(newImage.split(',')[1])


        const vals = {
          name: email,
          image: image2,
          is_company: false
        }

        await dispatch({
          type: 'partnerOrgModel/create',
          payload : {id: record.id, vals } ,
        });

        dispatch({
          type: 'partnerOrgModel/hide',
          payload: 'editForm'
        });
      }
    });
  }


  render() {
    const {
      dataSource: record,
      partnerOrgModel:{ visible },
      form: { getFieldDecorator }
    } = this.props;

    return (
      <div>
        <Modal title='分享'
          visible={visible.editForm}
          onOk={()=>this.handleOk()}
          onCancel={()=>this.handleCancel()}
        >
          <Form layout="inline">
            <FormItem label="url">
              {getFieldDecorator('email', {
                /*  rules: [{ required: true }], */
                initialValue: record.email,
              })(
                <Input />
              )}
            </FormItem>
            <FormItem label="二维码位置">
              {getFieldDecorator('ref', {
                /*  rules: [{ required: true }], */
                initialValue: record.ref,
              })(
                <Input />
              )}
            </FormItem>
          </Form>

            <img
              src={`data:image/jpeg;base64,${escape(record.image)}`}
              alt="example"
              style={{width: '30%',height:'30%' }}
            />

        </Modal>

      </div>
    );
  }
}

export default Form.create()(FormCreate);

